const app = getApp()

Page({
  data: {
    order: null,
    statusDescription: ''
  },

  onLoad(options) {
    const id = options.id
    this.loadOrderDetail(id)
  },

  loadOrderDetail(id) {
    const token = wx.getStorageSync('access_token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    wx.request({
      url: `${app.globalData.baseUrl}/orders/recycle-orders/${id}/`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const order = {
            ...res.data,
            status_display: this.getStatusDisplay(res.data.status),
            appointment_time: res.data.appointment_time.replace('T', ' ').split('.')[0]
          }
          this.setData({
            order,
            statusDescription: this.getStatusDescription(order.status)
          })
        } else {
          wx.showToast({
            title: '加载订单失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({ title: '加载订单失败', icon: 'none' });
      }
    })
  },

  getStatusDisplay(status) {
    const statusMap = {
      'pending': '待处理',
      'processing': '处理中',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return statusMap[status] || status
  },

  getStatusDescription(status) {
    const descMap = {
      'pending': '订单已提交，等待回收员接单',
      'processing': '回收员已接单，正在前往回收',
      'completed': '订单已完成',
      'cancelled': '订单已取消'
    }
    return descMap[status] || ''
  },

  cancelOrder() {
    const orderId = this.data.order.id
    wx.showModal({
      title: '确认取消',
      content: '确定要取消此订单吗？',
      success: (res) => {
        if (res.confirm) {
          const token = wx.getStorageSync('access_token')
          wx.request({
            url: `${app.globalData.baseUrl}/orders/recycle-orders/${orderId}/cancel/`,
            method: 'POST',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success'
                })
                setTimeout(() => {
                  wx.navigateBack()
                }, 1500)
              }
            }
          })
        }
      }
    })
  },

  evaluateOrder() {
    const orderId = this.data.order.id
    wx.navigateTo({
      url: `/pages/order-evaluate/order-evaluate?id=${orderId}`
    })
  },

  previewImage(e) {
    const url = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls
    wx.previewImage({
      current: url,
      urls
    })
  }
})